package com.blueocean_health.care.management.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.blueocean_health.care.management.common.LocalManager;
import com.blueocean_health.care.management.common.base.em.TimeType;
import com.blueocean_health.care.management.common.base.pinyin.Chinese2PinyinUtils;
import com.blueocean_health.care.management.common.base.string.StringUtils;
import com.blueocean_health.care.management.common.base.time.TimeUtils;
import com.blueocean_health.care.management.domain.base.NurseWorkerInfo;
import com.blueocean_health.care.management.domain.base.*;
import com.blueocean_health.care.management.domain.checkWorkVo.*;
import com.blueocean_health.care.management.domain.dto.SelectNurseDto;
import com.blueocean_health.care.management.domain.dto.SelectNurseGroupDto;
import com.blueocean_health.care.management.domain.dto.SelectNurseRespDto;
import com.blueocean_health.care.management.domain.groupvo.SelectNurseGroupVo;
import com.blueocean_health.care.management.em.GroupLeaderEnum;
import com.blueocean_health.care.management.em.LocalManagerType;
import com.blueocean_health.care.management.em.WorkCheckFlagEnum;
import com.blueocean_health.care.management.em.WorkStatusEnum;
import com.blueocean_health.care.management.exception.OrderException;
import com.blueocean_health.care.management.exception.OrderServiceException;
import com.blueocean_health.care.management.mapper.*;
import com.blueocean_health.care.management.mapper.NurseWorkerInfoMapper;
import com.blueocean_health.care.management.service.CheckWorkService;
import org.apache.poi.ss.formula.functions.Now;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.jws.Oneway;
import java.text.Collator;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author ChenPeng cp
 * @Date 2018/4/26 14:38
 */

@Service
public class CheckWorkServiceImpl implements CheckWorkService {

    @Autowired
    private NurseCheckWorkMapper nurseCheckWorkMapper;
    @Autowired
    private OrderServiceNurseInfoMapper orderServiceNurseInfoMapper;
    @Autowired
    private NurseGroupRelationMapper nurseGroupRelationMapper;
    @Autowired
    private NurseGroupMapper nurseGroupMapper;
    @Autowired
    private NurseWorkerInfoMapper nurseWorkerInfoMapper;


    @Override
    public SysResult queryNurseGroupListByHid(String hid) {
        //存小组名
        List<String> groupNameList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        //返回结果集
        List<NurseGroup> list = new ArrayList<>();

        List<NurseGroup> allNurseGroup = nurseCheckWorkMapper.queryNurseGroupListByHospital(hid);
        allNurseGroup.forEach(nurseGroup -> {
            groupNameList.add(nurseGroup.getGroupNamePy());
            map.put(nurseGroup.getGroupNamePy(), nurseGroup);
        });
        //汉字首字母排序
        Comparator<Object> com = Collator.getInstance(Locale.ENGLISH);
        Collections.sort(groupNameList, com);

        groupNameList.forEach(s -> {
            NurseGroup n = (NurseGroup) map.get(s);
            list.add(n);
        });

        NurseGroup nurseGroup = new NurseGroup();
        nurseGroup.setGroupId(0);
        nurseGroup.setGroupName("不限");
        list.add(0, nurseGroup);

        return SysResult.ok().addData(list);
    }

    @Override
    public SysResult queryNurseByHid(SelectNurseDto selectNurseDto) {
        //全部符合条件的护工
        selectNurseDto.setSort(null);
        List<SelectNurseRespDto> nurseList = orderServiceNurseInfoMapper.selectAllNurseContainQuit(selectNurseDto);
        //目前在小组内的所有护工，除了本组以外（为了防止点了移除操作但是没提交时，把护工再选进来）
        List<NurseGroupRelation> relations = nurseGroupRelationMapper.getAllMaxInfoByHospitalIdAndGroupId(selectNurseDto.getHospital(), selectNurseDto.getGroupId());
        //拿到ids
        List<String> workIdList = new ArrayList<>();
        relations.forEach(nurseGroupRelation -> {
            workIdList.add(nurseGroupRelation.getNurseId());
        });
        //查询当天已经有考勤记录的护工，防止临时组员被多个小组添加考勤（临时组员在上一个判断不会校验到）
        final List<NurseCheckWork> nurseCheckWorks = nurseCheckWorkMapper.queryAllByWorkTime(selectNurseDto.getCheckDate());
        nurseCheckWorks.forEach(nurseCheckWork -> workIdList.add(nurseCheckWork.getWorkId()));

        //包含护工id的数据表示不可被选择
        nurseList.forEach(vo -> {
            if (workIdList.contains(vo.getWorkerId())) {
                // 0：可选 1：不可选
                vo.setCheckFlag("1");
            } else {
                vo.setCheckFlag("0");
            }
        });
        List<SelectNurseRespDto> finresList = new ArrayList<>();
        //分页
        int first = (selectNurseDto.getPage() - 1) * selectNurseDto.getPageSize();
        int end = (first + selectNurseDto.getPageSize() > nurseList.size() ? nurseList.size() : first + selectNurseDto.getPageSize());
        for (int i = first; i < end; i++) {
            finresList.add(nurseList.get(i));
        }

        //查询当前已有小组的成员信息，找出护工在小组内的身份
        List<NurseGroupRelation> nurseGroupRelations = nurseGroupRelationMapper.getAllMaxInfoByHospitalId(selectNurseDto.getHospital());
        Map map = new HashMap();
        nurseGroupRelations.forEach(nurseGroupRelation -> map.put(nurseGroupRelation.getNurseId(), nurseGroupRelation.getLeaderFlag()));

        finresList.forEach(dto -> {
            if (map.containsKey(dto.getWorkerId())) {
                String leaderFlag = (String) map.get(dto.getWorkerId());
                dto.setLeaderFlag(leaderFlag);
                if (GroupLeaderEnum._1.getKey().equals(leaderFlag)) {
                    dto.setLeader(GroupLeaderEnum._1.getVal());
                } else if (GroupLeaderEnum._0.getKey().equals(leaderFlag)) {
                    dto.setLeader(GroupLeaderEnum._0.getVal());
                } else {
                    dto.setLeader("非小组成员");
                }
            } else {
                dto.setLeader("非小组成员");
            }
        });

        return SysResultByPage.ok(finresList, nurseList.size());
    }

    @Override
    public SysResult queryCheckWorkList(CheckWorkListDto checkWorkListDto, String flag) {
        //如果是 点击编辑考勤后的护工列表 接口，则校验一下groupid
        if (!StringUtils.isEmpty(checkWorkListDto.getCheckDate()) && "0".equals(checkWorkListDto.getGroupId())) {
            return SysResult.error("groupId字段错误");
        }
        List<CheckWorkListVo> lastList = this.queryCheckWorkListExcel(checkWorkListDto);
        //分页
        int first = (checkWorkListDto.getPage() - 1) * checkWorkListDto.getPageSize();
        int end = (first + checkWorkListDto.getPageSize() > lastList.size() ? lastList.size() : first + checkWorkListDto.getPageSize());
        List<CheckWorkListVo> finresList = new ArrayList<>();
        for (int i = first; i < end; i++) {
            CheckWorkListVo vo = lastList.get(i);
            finresList.add(vo);
        }
        return SysResultByPage.ok(finresList, lastList.size());
    }

    @Override
    public List<CheckWorkListVo> queryCheckWorkListExcel(CheckWorkListDto checkWorkListDto) {

        checkWorkListDto.setToday(TimeUtils.getTime(TimeType.yyyy_MM_dd));
        if (!StringUtils.isEmpty(checkWorkListDto.getCheckDate())) {
            checkWorkListDto.setToday(checkWorkListDto.getCheckDate());
        }
        List<CheckWorkListVo> checkWorkListVos = new ArrayList<>();
        //如果是查非小组成员的话，这个方法就查不到，最后计算临时成员的时候就出现数据错误
        //所以需要手动查一下
        List<CheckWorkListVo> groupNurseCheck = new ArrayList<>();
        if (GroupLeaderEnum._2.getKey().equals(checkWorkListDto.getTitle())) {
            String finalTitle = checkWorkListDto.getTitle();
            CheckWorkListDto newDto = checkWorkListDto;
            newDto.setTitle(GroupLeaderEnum._1.getKey());
            groupNurseCheck = nurseCheckWorkMapper.queryCheckWorkList(newDto);
            newDto.setTitle(GroupLeaderEnum._0.getKey());
            final List<CheckWorkListVo> leaderCheckWork = nurseCheckWorkMapper.queryCheckWorkList(newDto);
            groupNurseCheck.addAll(leaderCheckWork);
            newDto.setTitle(finalTitle);
        } else {
            //不包括临时组员的数据集合（已区分组长组员）
            groupNurseCheck = nurseCheckWorkMapper.queryCheckWorkList(checkWorkListDto);
        }

        //过滤掉（A护工先被B小组以临时成员的形式加入当天弄考勤， C小组又吧A护工在小组管理中加入小组，此时A护工是会被以组员的形式查询出来）这部分数据
        checkWorkListVos = groupNurseCheck.stream().filter(vo -> {
            NurseGroupRelation n = nurseGroupRelationMapper.queryInfoByWorkId(vo.getWorkerId());
            //如果该护工当前所在和考勤小组一致，才符合条件
            return n.getGroupId().equals(vo.getGroupId());
        }).collect(Collectors.toList());

        //包含临时组员的集合
        List<CheckWorkListVo> allVos = nurseCheckWorkMapper.queryCheckWorkListAndTemporary(checkWorkListDto);
        //只有临时组员的集合
        List<CheckWorkListVo> temporaryVos = new ArrayList<>();
        if (allVos.size() > checkWorkListVos.size()) {
            Map map = new HashMap();
            //存放所有非临时成员的workid
            checkWorkListVos.forEach(vo -> map.put(vo.getWorkerId(), vo));
            //剔除非临时成员
            allVos.forEach(vo -> {
                if (!map.containsKey(vo.getWorkerId())) {
                    temporaryVos.add(vo);
                }
            });
        }

        List<CheckWorkListVo> lastList = new ArrayList<>();
        //根据条件参数，选择需要排序分页的集合
        String title = checkWorkListDto.getTitle();
        if (GroupLeaderEnum._1.getKey().equals(title)) {
            lastList = checkWorkListVos;
        } else if (GroupLeaderEnum._0.getKey().equals(title)) {
            lastList = checkWorkListVos;
        } else if (GroupLeaderEnum._2.getKey().equals(title)) {
            lastList = temporaryVos;
        } else {
            //全部
            lastList.addAll(temporaryVos);
            lastList.addAll(checkWorkListVos);
        }

        //以小组来排序
        Collections.sort(lastList);

        lastList.forEach(vo -> {
            if (WorkStatusEnum._0.getKey().equals(vo.getWorkStatus())) {
                vo.setWorkStatusName(WorkStatusEnum._0.getVal());
            } else if (WorkStatusEnum._1.getKey().equals(vo.getWorkStatus())) {
                vo.setWorkStatusName(WorkStatusEnum._1.getVal());
            } else if (WorkStatusEnum._2.getKey().equals(vo.getWorkStatus())) {
                vo.setWorkStatusName(WorkStatusEnum._2.getVal());
            } else {
            }

            if (GroupLeaderEnum._1.getKey().equals(vo.getTitle())) {
                vo.setTitle(GroupLeaderEnum._1.getVal());
                vo.setTitleKey(GroupLeaderEnum._1.getKey());
            } else if (GroupLeaderEnum._0.getKey().equals(vo.getTitle())) {
                vo.setTitle(GroupLeaderEnum._0.getVal());
                vo.setTitleKey(GroupLeaderEnum._0.getKey());
            } else {
                vo.setTitle(GroupLeaderEnum._2.getVal());
                vo.setTitleKey(GroupLeaderEnum._2.getKey());
            }

            vo.setWorkTimeStr(TimeUtils.getStringByDate(vo.getWorkTime(), TimeType.yyyy_MM_dd));
        });

        return lastList;
    }


    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SysResult updateCheckWorkByGroup(UpdateCheckWorkVo updateCheckWorkVo) throws OrderException {

        Date workTime = updateCheckWorkVo.getCheckDate();
        String stringTime = TimeUtils.getStringByDate(updateCheckWorkVo.getCheckDate(), TimeType.yyyy_MM_dd);
        Integer groupId = updateCheckWorkVo.getGroupId();

        //根据小组id和日期找到老数据（不包含移除的）
        List<NurseCheckWork> lastInfo = nurseCheckWorkMapper.queryLastInfoByTimeAndGroup(stringTime, groupId);
        //如果没有，则是添加，
        Date createTime = new Date();
        Date updateTime = new Date();
        final List<CheckWorkListVo> newInfoes = updateCheckWorkVo.getList();

        if (lastInfo.size() < 1) {
            newInfoes.forEach(infovo -> {
                NurseCheckWork info = new NurseCheckWork();
                info.setWorkId(infovo.getWorkerId());
                info.setWorkStatus(infovo.getWorkStatus());
                info.setGroupId(groupId);
                info.setWorkTime(workTime);
                info.setDeflag("0");
                info.setCreateTime(createTime);
                info.setUpdateTime(updateTime);
                info.setWorkName(infovo.getWorkName());
                String pinyinAll = Chinese2PinyinUtils.toPinyinAll(info.getWorkName());
                info.setWorkPyname(pinyinAll);
                nurseCheckWorkMapper.insert(info);
            });
        } else {
            //有数据代表本次为修改
            //老数据中有，但是新数据没有的workid为移除状态，
            List<String> lastWorks = new ArrayList<>();
            List<String> newWorks = new ArrayList<>();
            List<String> oldWorks = new ArrayList<>();
            lastInfo.forEach(nurseCheckWork -> lastWorks.add(nurseCheckWork.getWorkId()));
            newInfoes.forEach(newInfo -> newWorks.add(newInfo.getWorkerId()));


            lastWorks.forEach(s -> {
                //修改这部分数据为移除状态
                if (!newWorks.contains(s)) {
                    boolean dbflag = nurseCheckWorkMapper.deleteCheckWorkByGroupAndWorker(stringTime, s, groupId);
                } else {
                    oldWorks.add(s);
                }
            });

            //其余的数据也更新一下
            newInfoes.stream().filter(vo -> oldWorks.contains(vo.getWorkerId())).forEach(vo -> {
                nurseCheckWorkMapper.updateCheckWorkByGroupAndWorker(vo.getWorkStatus(), stringTime, vo.getWorkerId(), vo.getGroupId());
            });

            //新数据中有，老数据中没有的为新添加的数据，新增这部分数据
            List<String> lastWorks2 = new ArrayList<>();
            List<String> newWorks2 = new ArrayList<>();
            lastInfo.forEach(nurseCheckWork -> lastWorks2.add(nurseCheckWork.getWorkId()));
            newInfoes.forEach(newInfo -> newWorks2.add(newInfo.getWorkerId()));

            newWorks2.removeAll(lastWorks2);
            newInfoes
                    .stream()
                    .filter(checkWorkListVo -> newWorks2.contains(checkWorkListVo.getWorkerId()))
                    .forEach(checkWorkListVo -> {
                        NurseCheckWork info = new NurseCheckWork();
                        info.setWorkId(checkWorkListVo.getWorkerId());
                        info.setWorkStatus(checkWorkListVo.getWorkStatus());
                        info.setGroupId(groupId);
                        info.setWorkTime(workTime);
                        info.setDeflag("0");
                        info.setCreateTime(createTime);
                        info.setUpdateTime(updateTime);
                        info.setWorkName(checkWorkListVo.getWorkName());
                        String pinyinAll = Chinese2PinyinUtils.toPinyinAll(info.getWorkName());
                        info.setWorkPyname(pinyinAll);
                        int insert = nurseCheckWorkMapper.insert(info);
                    });
        }

        return SysResult.ok();
    }

    @Override
    public SysResult queryMonthCheckByWorker(SelectMonthDto selectMonthDto) {
        if (StringUtils.isEmpty(selectMonthDto.getWorkerId()) || StringUtils.isEmpty(selectMonthDto.getEndDate()) || StringUtils.isEmpty(selectMonthDto.getStartDate())) {
            return SysResult.error("参数不可为空");
        }
        List<SelectMonthVo> nurseCheckWorks = nurseCheckWorkMapper.queryMonthCheckByWorker(selectMonthDto.getWorkerId(), selectMonthDto.getStartDate(), selectMonthDto.getEndDate());
        nurseCheckWorks.forEach(selectMonthVo -> {
            if (WorkStatusEnum._0.getKey().equals(selectMonthVo.getWorkStatus())) {
                selectMonthVo.setWorkStatusName(WorkStatusEnum._0.getVal());
            } else if (WorkStatusEnum._1.getKey().equals(selectMonthVo.getWorkStatus())) {
                selectMonthVo.setWorkStatusName(WorkStatusEnum._1.getVal());
            } else {
                selectMonthVo.setWorkStatusName(WorkStatusEnum._2.getVal());
            }
        });

        return SysResult.ok().addData(nurseCheckWorks);
    }

    @Override
    public Map<String, Long> queryAllByStartAndEndTime(String startTime, String endTime) {
        List<NurseCheckWork> nurseCheckWorks = nurseCheckWorkMapper.queryAllByStartAndEndTime(startTime, endTime);
        Map<String, Long> collect = nurseCheckWorks.stream().collect(Collectors.groupingBy(NurseCheckWork::getWorkId, Collectors.counting()));
        return collect;
    }

    @Override
    public Map<Integer, Long> queryAllByGroupId(String startTime, String endTime) {
        List<NurseCheckWork> nurseCheckWorks = nurseCheckWorkMapper.queryAllByStartAndEndTime(startTime, endTime);
        Map<Integer, Long> collect = nurseCheckWorks.stream().collect(Collectors.groupingBy(NurseCheckWork::getGroupId, Collectors.counting()));
        return collect;
    }

    @Override
    public Long queryByGroupId(Integer groupId, String startTime, String endTime) {
//        Map<Integer, Long> collect = this.queryAllByGroupId(startTime,endTime);
//        Long result = 0L;
//        if (collect.containsKey(groupId)){
//             result = (Long)collect.get(groupId);
//        }
        return nurseCheckWorkMapper.queryByGroupId(groupId, startTime, endTime);
    }

    @Override
    public Integer queryByWorkIdAndGroupId(String workId, String groupId, String startTime, String endTime) {
        return nurseCheckWorkMapper.queryByWorkIdAndGroupId(workId, groupId, startTime, endTime);
    }


    @Override
    public Long queryByWorkId(String workId, String startTime, String endTime) {
//        Map<String, Long> collect = this.queryAllByStartAndEndTime(startTime,endTime);
//        Long result = 0L;
//        if (collect.containsKey(workId)){
//            result = (Long)collect.get(workId);
//        }
        return nurseCheckWorkMapper.queryByWorkerId(workId, startTime, endTime);
    }

    @Override
    public List<SelectGroupVo> queryAllByStartAndEndTimeAndGroupId(String startTime, String endTime) {
        List<NurseCheckWork> nurseCheckWorks = nurseCheckWorkMapper.queryAllByStartAndEndTime(startTime, endTime);
        Map<String, Long> collect = nurseCheckWorks
                .stream()
                .collect(Collectors.groupingBy(o -> {
                    NurseCheckWork u = (NurseCheckWork) o;
                    return u.getWorkId() + "," + u.getGroupId();
                }, Collectors.counting()));

        List<SelectGroupVo> result = new ArrayList<>();

        for (Map.Entry<String, Long> entry : collect.entrySet()) {
            SelectGroupVo vo = new SelectGroupVo();
            String key = entry.getKey();
            String[] split = key.split(",");
            if (split.length > 1) {
                vo.setNurseId(split[0]);
                vo.setGroupId(Integer.parseInt(split[1]));
                vo.setAttendanceDays(entry.getValue());
                result.add(vo);
            }
        }
        return result;
    }


    /**
     * 批量修改考勤记录
     *
     * @param data,json数据结构 {
     *                      "worker_id":"15265459970827626699",
     *                      "group_id":"1770",
     *                      "start_time":"2017-05-01",
     *                      "end_time":"2017-05-30",
     *                      "records":[
     *                      {
     *                      "work_time":"2018-05-27",
     *                      "work_status":0
     *                      }
     *                      ]
     *                      }
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void updateCheckWorkBatch(JSONObject data) throws OrderException {
        String worker_id = data.getString("worker_id");
        Integer group_id = data.getInteger("group_id");
        Date startTime = data.getDate("start_time");
        Date endTime = data.getDate("end_time");
        JSONArray records = data.getJSONArray("records");

        NurseWorkerInfo workerInfo = nurseWorkerInfoMapper.selectMainByWorkerId(worker_id);
        /**
         * 检查护工id有效性
         */
        if (StringUtils.isEmpty(workerInfo)) {
            throw new OrderException("非法的护工id，worker_id:" + worker_id);
        }
        /**
         * 检查小组id有效性
         */
        if (StringUtils.isEmpty(group_id)) {
            throw new OrderException("非法的小组id，group_id:" + worker_id);
        }

        Date now_date = new Date();
        List<NurseCheckWork> checkWorks = new ArrayList<>();
        for (int i = 0; i < records.size(); i++) {
            JSONObject record = records.getJSONObject(i);
            Date work_time = record.getDate("work_time");
            String work_status = record.getString("work_status");
            if (now_date.getTime() < work_time.getTime()) {
                throw new OrderException("修改的考勤记录不能超过当前日期.");
            }
            NurseCheckWork checkWork = new NurseCheckWork();
            checkWork.setCreateTime(now_date);
            checkWork.setDeflag("0");
            checkWork.setGroupId(group_id);
            checkWork.setUpdateTime(now_date);
            checkWork.setWorkId(worker_id);
            checkWork.setWorkStatus(work_status);
            checkWork.setWorkTime(work_time);
            checkWork.setWorkName(workerInfo.getWorkerName());
            checkWork.setWorkPyname(workerInfo.getWorkerNamePinYin());
            checkWorks.add(checkWork);
        }

        /**
         * 删除指定日期
         */
        if (now_date.getTime() < endTime.getTime()) {
            endTime = now_date;
        }
        nurseCheckWorkMapper.deleteWorkCheckByTime(startTime, endTime, worker_id);
        /**
         * 插入指定记录
         */
        nurseCheckWorkMapper.insertList(checkWorks);

    }

    @Override
    public SysResult queryWorkerListForCheckWork(String workId,String hid) {
        NurseGroupRelation relation = nurseGroupRelationMapper.queryInfoByWorkId(workId);
        List<WorkListVo> workListVos = new ArrayList<>();
        if (relation == null){
            return SysResult.ok().addData(workListVos);
        }
        //查看该小组最新版成员有没有当前护工（如果护工进入该组又移除后，要进行这样的校验）
        List<String> workIds = nurseGroupMapper.getAllWorkIdsByGroupId(relation.getGroupId());
        if (workIds == null || workIds.size() < 1) {
            return SysResult.ok().addData(workListVos);
        }else if (!workIds.contains(relation.getNurseId())){
            return SysResult.ok().addData(workListVos);
        }else {
            workListVos= nurseGroupRelationMapper.queryWorkerListForCheckWork(relation.getGroupId());
        }
        return SysResult.ok().addData(workListVos);
    }

    @Override
    public SysResult queryCheckWorkListNew(CheckWorkListNewDto checkWorkListNewDto) {
        List<CheckWorkListNewVo> lastList = this.queryCheckWorkListExcelNew(checkWorkListNewDto);
        //分页
        int first = (checkWorkListNewDto.getPage() - 1) * checkWorkListNewDto.getPageSize();
        int end = (first + checkWorkListNewDto.getPageSize() > lastList.size() ? lastList.size() : first + checkWorkListNewDto.getPageSize());
        List<CheckWorkListNewVo> finresList = new ArrayList<>();
        for (int i = first; i < end; i++) {
            CheckWorkListNewVo vo = lastList.get(i);
            finresList.add(vo);
        }
        return SysResultByPage.ok(finresList, lastList.size());
    }

    @Override
    public List<CheckWorkListNewVo> queryCheckWorkListExcelNew(CheckWorkListNewDto checkWorkListNewDto) {
        //最终结果集
        List<CheckWorkListNewVo> result = new ArrayList<>();
        //当前医院所有时间段内，符合查询条件的基础数据
        List<CheckWorkListNewVo> newList = nurseCheckWorkMapper.queryCheckWorkNewList(checkWorkListNewDto);
        //存放数据集去重后的workid
        Set set = new HashSet();
        newList.forEach(checkWorkListNewVo -> set.add(checkWorkListNewVo.getWorkId()));
        set.forEach(o -> {
            Long workDay = newList.stream().filter(vo -> vo.getWorkId().equals(o) && vo.getWorkStatus().equals(WorkStatusEnum._0.getKey())).count();
            Long lackDay = newList.stream().filter(vo -> vo.getWorkId().equals(o) && vo.getWorkStatus().equals(WorkStatusEnum._1.getKey())).count();
            Long restDay = newList.stream().filter(vo -> vo.getWorkId().equals(o) && vo.getWorkStatus().equals(WorkStatusEnum._2.getKey())).count();
            CheckWorkListNewVo firstVo = newList.stream().filter(vo -> vo.getWorkId().equals(o)).findFirst().orElse(null);

            if (firstVo != null) {
                CheckWorkListNewVo checkWorkListNewVo = new CheckWorkListNewVo();
                checkWorkListNewVo.setWorkDay(workDay);
                checkWorkListNewVo.setLackDay(lackDay);
                checkWorkListNewVo.setRestDay(restDay);
                checkWorkListNewVo.setWorkId(firstVo.getWorkId());
                checkWorkListNewVo.setWorkName(firstVo.getWorkName());

                //查出该时间段，所有涉及的组
                List<CheckWorkListNewVo> listByWorkId = nurseCheckWorkMapper.queryInfoByWorkIdAndTime(checkWorkListNewDto.getStartTime(), checkWorkListNewDto.getEndTime(), firstVo.getWorkId());
                Set<String> groupNameSet = new HashSet();
                listByWorkId.forEach(vo -> groupNameSet.add(vo.getGroupName()));
                //拼接组名
                StringBuffer groupName = new StringBuffer();
                groupNameSet.forEach(s -> {
                    if (groupName.length() == 0){
                        groupName.append(s);
                    }else {
                        groupName.append("/").append(s);
                    }
                });
                checkWorkListNewVo.setGroupName(groupName.toString());
                result.add(checkWorkListNewVo);
            }
        });
        return result;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public SysResult updateCheckWorkNew(UpdateCheckWorkNewVo dto) throws OrderException {
        //删除该护工该日期所有考勤数据
        Integer integer = nurseCheckWorkMapper.updateCheckWorkNew(dto.getCheckDate(), dto.getWorkId());
        //新增该日期考勤数据
        Date now = new Date();
        NurseCheckWork work = new NurseCheckWork();
        work.setWorkStatus(dto.getWorkStatus());
        work.setWorkId(dto.getWorkId());
        work.setWorkName(dto.getWorkName());
        work.setCreateTime(now);
        work.setUpdateTime(now);
        work.setDeflag("0");
        work.setGroupId(dto.getGroupId());
        work.setWorkPyname(Chinese2PinyinUtils.toPinyinAll(dto.getWorkName()));
        work.setWorkTime(TimeUtils.getDateByString(dto.getCheckDate(),TimeType.yyyy_MM_dd));
        int insert = nurseCheckWorkMapper.insert(work);
        if (insert < 1){
            throw new OrderException("编辑考勤失败！");
        }
        return SysResult.ok();
    }


    public static void main(String[] args){}
}
